﻿using System.Collections.Concurrent;
using System.Reflection;
using Microsoft.Extensions.Configuration;

namespace Sol_NetCoreReadConfig.Settings
{
    /// <summary>
    /// 添加不同环境的appsettings.json
    /// </summary>
    public static class AppConfigurations
    {
        private static readonly ConcurrentDictionary<string, IConfigurationRoot> _configurationCache;

        static AppConfigurations()
        {
            _configurationCache = new ConcurrentDictionary<string, IConfigurationRoot>();
        }

        public static IConfigurationRoot Get(string jsonDir, string environmentName = null)
        {
            // 添加默认的 JSON 配置
            var builder = new ConfigurationBuilder().SetBasePath(jsonDir).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            // 根据环境变量添加相应的 JSON 配置文件
            if (!string.IsNullOrWhiteSpace(environmentName))
            {
                builder = builder.AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: true);
            }

            // 返回构建成功的 IConfigurationRoot 对象
            return builder.Build();
        }
    }
}
